#!/bin/bash

debug=false

FILE=/tmp/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa # $( tempfile )
FILE_NEW=/tmp/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb  # $( tempfile )

FILE_TO_WRITE_ACTIVE_HOSTS=/var/www/qsearch/active_hosts
APPEND=.pw.edu.pl

#SLEEPTIME=120 # in sec

#while sleep $SLEEPTIME; do

#	echo ------------- scan ------------------
#	smbtree -d0 -N > $FILE_NEW
#	echo after scan
#
#	list=$( cat $FILE_NEW | grep -P "^\t\t[^\t]" | awk '{print $1}' | sed 's:\\\\\([^\\]*\)\\.*:\1:' | sort | uniq )
#	echo "$list"
#	echo diff $FILE_NEW $FILE
###	diff $FILE_NEW $FILE
#	
#	echo "$list" > $FILE_TO_WRITE_ACTIVE_HOSTS	
#	
#	cp $FILE_NEW $FILE


	kids=( '' )
	test -f $FILE_NEW && rm $FILE_NEW


	hosts=$( mysql -u serwus --password=serwus123 qsearch -e "SELECT DISTINCT hostname FROM qsearch5 order by hostname;" | tail -n +2 )
	$debug && echo $hosts

	# ping hosts symultanuously
	for i in $hosts; do
		i=$i$APPEND
		echo $i
		$debug && echo "ping -c1 $i >/dev/null 2>/dev/null && echo $i >> $FILE_NEW"
		( ping -c1 $i >/dev/null 2>/dev/null && echo $i >> $FILE_NEW ) & 
		kids=( ${kids[@]} $! )
	done
	$debug && echo "wait ${kids[@]}"
	wait ${kids[@]}

	cp $FILE_NEW $FILE_TO_WRITE_ACTIVE_HOSTS

	# echo next

#done	


